const Jwt = require('jsonwebtoken') // 解析 token
const {
    jwt_config
} = global.config
const secretKey = jwt_config.serect
const expiresIn = jwt_config.expiresIn

// 解析
async function getToken(ctx, next) {
    let url = ctx.request.url
    // 白名单
    const whiteList = [
        '/api/v1/admin/admin/login', // 管理员登录
        '/api/v1/admin/admin/login/token', // 管理员token登录
        '/api/v1/client', // 客户端
    ]
    // 白名单以外的则校验
    const auth = whiteList.find(item => {
        return url.includes(item)
    })
    if (auth) {
        await next()
    } else {
        const token = ctx.req.headers.authorization
        let errMsg = "无效的token"
        // 没有token
        if (!token) {
            errMsg = "需要携带token"
            global.Response.authFail(ctx)
            return false
        }
        // 解析token
        try {
            var decode = Jwt.verify(token, secretKey)
            ctx.auth = {
                uid: decode.uid,
                auth: decode.auth // scope
            }
            /* --------------- 检查权限 ----------------- */
            // get, post, put, delete
            let reqMethod = ctx.request.method
            const scope = decode.auth.toString().split("")
            if ((reqMethod == 'POST' && scope[1] != 1) || (reqMethod == 'DELETE' && scope[3] != 1) || (reqMethod == 'PUT' && scope[2] != 1) || (reqMethod == 'GET' && scope[0] != 1)) {
                console.log("没有权限")
                global.Response.fail(ctx, `抱歉，没有${reqMethod}权限`)
                return false
            }
        } catch (error) {
            // token 不合法 过期
            if (error.name === 'TokenExpiredError') {
                errMsg = "token已过期"
            }
            global.Response.authFail(ctx, errMsg)
        }
        await next()
    }
}

module.exports = getToken